<script setup>
import { uploadImageAction } from "@/api/image"
import { getToken } from "@/composables/auth"
import { toast } from "@/composables/util"

// 接受外部传入的图库id
defineProps({
  data: Object
})
// 获取 token
const token = getToken()
// 向外提供内部事件
const emit = defineEmits(["success"])

// 上传成功
const uploadSuccess = (response, uploadFile, uploadFiles) => {
  emit("success", {
    response,
    uploadFile,
    uploadFiles
  })
  // 清空文件列表
  uploadFiles.splice(0, uploadFiles.length)
}

// 上传失败
const uploadError = (error, uploadFile, uploadFiles) => {
  let msg = JSON.parse(error.message).msg || "上传失败"
  toast(msg, "error")
}
</script>

<template>
  <el-upload
    drag
    :action="uploadImageAction"
    :headers="{
      token
    }"
    name="img"
    :data="data"
    :on-success="uploadSuccess"
    :on-error="uploadError"
  >
    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
    <div class="el-upload__text">
      将文件拖到此处
      <em>点击上传</em>
    </div>
    <template #tip>
      <div class="el-upload__tip">图片格式为：jpg/png；大小请不要超过500kb</div>
    </template>
  </el-upload>
</template>
